// add by yanyj 20180724 start
// 流量观测点layer
class GcdLayer extends BaseLayer {
    // 构造函数
    constructor(name) {
        super(name);
        this.drawInteraction = null; // 画笔
        this.overLayer = null; // 弹出层
        this.drawFeature = null; // 正在画的feature
        this.fetch = new Fetch(pageLogic.initData.restUrlPrefix);

        this.featureType = 'gcd';
        this.formInit = false;
        // 设置Validation
        this.validation = this.getValidation();

        // this.init();
    }

    init() {
        // 观测点图层
        let observablePintSource = new ol.source.Vector();
        this.setLayer(new ol.layer.Vector({
            source: observablePintSource,
            style: function (feature) {
                feature.name = feature.name || '';
                let coordinates = feature.getGeometry().getCoordinates();
                let start = coordinates[0];
                let end = coordinates[1];
                // 为了标签都从左向右绘制
                if(start[0] > end[0]) {
                    end = coordinates[0];
                    start = coordinates[1];
                }
                let dx = end[0] - start[0];
                let dy = end[1] - start[1];
                let rotation = 0;
                // if((dy >=0 && dx >=0) || (dy <=0 && dx <=0)) {
                    rotation = Math.atan2(dy, dx);
                // } else {
                //     rotation = Math.atan2(-dy, -dx);
                // }
                // rotation = rotation >=0 ? rotation : rotation + 3;
                return new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 0.2)'
                    }),
                    stroke: new ol.style.Stroke({
                        color: '#ffcc33',
                        width: 2
                    }),
                    image: new ol.style.Circle({
                        radius: 7,
                        fill: new ol.style.Fill({
                            color: '#ffcc33'
                        })
                    }),
                    text: new ol.style.Text({
                        text: feature.name,
                        fill: new ol.style.Fill({
                            color: '#fffefd'
                        }),
                        font: '12px 宋体',
                        placement: 'point',
                        // 设置背景填充
                        backgroundFill: new ol.style.Fill({
                            color: '#066ab5'
                        }),
                        backgroundStroke: new ol.style.Stroke({
                            color: '#004579'
                        }),
                        padding: [6, 6, 6, 6],
                        rotation: -rotation
                    })
                })
            }
        }));

        // 新建观测点画笔
        this.drawInteraction = createDraw('LineString', observablePintSource);

        // 设置state 和 action
        let _this = this;
        _this.setStateAndAction({
            list: [],
            draw: false
        }, {
            list: (target, proxy, value, obj) => {
                _this.addFeatures(value)
            },
            draw: function (target, proxy, value, obj) {
                // _this.showOverLayer(undefined);



                value ? _this.activeDraw(_this.drawInteraction) : _this.inactiveDraw(_this.drawInteraction)
            }
        });

        this.initOverLayer();
        this.register();
        return this;
    }

    createFeatures(data) {
        let featureType = this.featureType;
        let features = [];

        pocket.forEach(data, gcd => {
            if (coordtransform.out_of_china(+gcd.qdjd, +gcd.qdwd) || coordtransform.out_of_china(+gcd.zdjd, +gcd.zdwd)) {
                return;
            }
            let start = coordtransform.lonlatTomercator([+gcd.qdjd, +gcd.qdwd]);
            let end = coordtransform.lonlatTomercator([+gcd.zdjd, +gcd.zdwd]);
            let feature = new ol.Feature({
                geometry: new ol.geom.LineString([start, end]),
            });

            feature.id = gcd.id;
            feature.attributes = gcd;
            feature.name = gcd.gcdmc;
            feature.type = featureType;
            features.push(feature);

        });

        return features;
    }

    getClickFeatureEvent() {
        let _this = this;
        return (feature, coordinate) => {
            _this.fetch.get(`/gcds/${feature.id}`, {})
                .then(res => {
                    let info = res.data;
                    info.start = `${info.qdjd},${info.qdwd}`;
                    info.end = `${info.zdjd},${info.zdwd}`;

                    _this.showOverLayer(coordtransform.lonlatTomercator([+info.zdjd, +info.zdwd]), info, 'info');
                })
        }
    }

    register() {
        let _this = this;
        // 画笔事件
        let listener;
        let sketch;

        this.drawInteraction.on('drawstart', function (evt) {
            // set sketch
            sketch = evt.feature;
            _this.drawFeature = sketch;
            /** @type {ol.Coordinate|undefined} */

            listener = sketch.getGeometry().on('change', function (evt) {
                let geom = evt.target;
                if (geom.getCoordinates().length === 3) {
                    _this.drawInteraction.finishDrawing();
                    _this.setState('draw', false);
                    let startXY = ol.proj.toLonLat(geom.getCoordinates()[0]).map(value => value.toFixed(6));
                    let endXY = ol.proj.toLonLat(geom.getCoordinates()[1]).map(value => value.toFixed(6));
                    // _this.$form[0].reset();
                    // $('#startCoordinate').val(startXY.join(','));
                    // $('#endCoordinate').val(endXY.join(','));
                    //
                    // _this.overLayer.setPosition(geom.getCoordinates()[1]);
                    _this.showOverLayer(geom.getCoordinates()[1], {
                        start: startXY.join(','),
                        end: endXY.join(',')
                    })
                }


            });
        }, this);

        this.drawInteraction.on('drawend', function () {

            // unset sketch
            sketch = null;
            // unset tooltip so that a new one can be created

        }, this);

        // 页面事件 观测点图层勾选
        $('#gcdLayer').on('click', function () {
            if ($(this).prop('checked')) {
                // 展示操作图层
                $('#observablePointLayerOption').show();
                _this.getAllGcds();
            } else {
                // 隐藏操作图层
                $('#observablePointLayerOption').hide();
                // 改变state
                _this.setState('list', []);
            }
        });

        // 新建流量观测点
        $('#addObservablePoint').on('click', () => {
            _this.setState('draw', true);
        });

        // 新建form
        $('#opName').on('input', function () {
            _this.drawFeature.name = $(this).val();
            _this.layer.getSource().refresh();
        });
        // 取消新增
        $('#cancelObservablePointBtn').on('click', function () {
            $('#observablePointPopup').find('.ol-popup-closer').click();
        });

        // 新增保存事件
        $('#addObservablePointBtn').on('click', function () {
            _this.save();
        });

        return this;

    }

    // 激活画画控件
    activeDraw(interaction) {
        this.map.getMap().addInteraction(interaction);
    }

    // 失活画画控件
    inactiveDraw(interaction) {
        this.map.getMap().removeInteraction(interaction)
    }

    // 初始化弹出层
    initOverLayer() {
        let _this = this;

        this.overLayer = new ol.Overlay({
            element: document.getElementById('observablePointPopup'),
            autoPan: true,
            autoPanAnimation: {
                duration: 250
            }
        });

        this.map.addOverLayer('gcdOver', this.overLayer, function (close) {
            if(_this.overLayer.getElement().dataset.action === 'save') {
                LayerTip.confirm('确定取消本次新增观测点【将不保留本次编辑信息】？', function () {
                    close();
                    _this.map.removeFeature(_this.layer, _this.drawFeature);
                    _this.drawFeature = null;
                    LayerTip.success('关闭成功');
                }, function () {

                })
            } else {
                close();
                LayerTip.success('关闭成功');
            }

        });

        this.initForm({});
        $('#observablePointPopup').show();

        return this;

    }

    getAllGcds() {
        let _this = this;
        this.fetch.get('/gcds', {}).then(res => {
            _this.setState('list', res.data);
        })
    }


    initForm(data) {

        // 初始化管理单位树
       this.management = $("#opManagement").selectTree({
            url: masterpage.ctxp + "/sys/orgs/-1/tree"
        });

        // 航道
        $("#opChannel").select({
            url: masterpage.ctxp + "/basic/hds/getAllhd",
            textField: "hdmc",
            valueField: "id",
            responseKey: "data",
            headerKey: "请选择",
            headerValue: ""
        });

        // 航段关联刷新
        $("#opChannel").on("change", function () {
            let hdId = $("#opChannel").val() || "-1";
            $("#opLeg").select({
                url: masterpage.ctxp + "/basic/hts/" + hdId + "/getHtByHdId",
                textField: "htmc",
                valueField: "id",
                responseKey: "data"
            });
        });

        // 行政区划
        common.dictSelect({
            id: "opArea",
            key: "XZQH"
        });

        this.$form = $('#observablePointPopup').find('form');
        this.formInit = true;
    }

    // 展示弹出层
    showOverLayer(position, data, action) {
        if(!this.formInit) {
            this.initForm({});
        }
        let $form = this.$form;
        let managementTree = this.management;
        $form[0].reset();
        $(`[name=htpk]`).html('');
        managementTree.checkAllNodes(false);
        this.overLayer.getElement().dataset.action = action || 'save';
        if(action === 'info') {
            $form.find('.info-value > *').prop('disabled', 'disabled');
            $('#addObservablePointBtn').hide();
        } else {
            $form.find('.info-value > *').prop('disabled', '');
            $('#addObservablePointBtn').show();
        }
        pocket.keys(data).forEach((key) => {
            if ($form.find(`[name=${key}]`).val) {
                if(key === 'htpk') {
                    $(`[name=hdpk]`).change();
                } else if(key === 'gljgid') {
                    managementTree.checkNodeById(data[key]);
                }
                $form.find(`[name=${key}]`).val(data[key]);
            } else {
                throw new Error(`初始化form时[name=${key}异常]`);
            }

        });

        this.overLayer.setPosition(position);

        return this;

    }

    // 设置校验规则
    getValidation() {
        return new Validation({
            validMethod: 'tooltip',
            rules: {
                gcdmc:  {  // 观测点名称
                    required: Validation.METHODS.required
                },
                gcdbh:  {  // 观测点编号
                    required: Validation.METHODS.required
                },
                gcdjgid:  {  // 观测点编号
                    required: Validation.METHODS.required
                },
                start:  {  // 观测点编号
                    required: Validation.METHODS.required,
                    legal: function (value) {
                        let starts = value.split(',');

                        return starts.length === 2 && +starts[0] > 0 && +starts[1] > 0;
                    }
                },
                end:  {  // 观测点编号
                    required: Validation.METHODS.required,
                    legal: function (value) {
                        let ends = value.split(',');

                        return ends.length === 2 && +ends[0] > 0 && +ends[1] > 0;
                    }
                },
                hdpk:{
                    required: Validation.METHODS.required,
                },
                htpk:{
                    required: Validation.METHODS.required,
                },
                xzqhid: {
                    required: Validation.METHODS.required,
                }
            },
            messages: {
                gcdmc: {
                    required:  '观测点名称为必填项'
                },
                gcdbh: {
                    required:  '观测点编号为必填项'
                },
                gcdjgid: {
                    required:  '管理单位为必填项'
                },
                start: {
                    required:  '起点坐标为必填项',
                    legal: '起点坐标非法'
                },
                end: {
                    required:  '终点坐标为必填项',
                    legal: '终点坐标非法'
                },
                hdpk:{
                    required: '航道为必填项',
                },
                htpk:{
                    required: '航段为必填项',
                },
                xzqhid: {
                    required:  '行政区划为必填项',
                }
            }
        });
    }

    // 保存
    save() {
        let _this = this,
        info = _this.getFormData();

        // info 重新组装
        info.gljgid = info.opManagement_hidden;
        let start =  info.start.split(',');
        let end =  info.end.split(',');
        info.qdjd = start[0];
        info.zdjd = end[0];
        info.qdwd = start[1];
        info.zdwd = end[1];

        if(!_this.validation.valid(info)) {
            return;
        }
        _this.fetch.post('/gcds', info)
            .then(res => {
                if(res.success) {
                    _this.drawFeature.id = res.data[0];
                    LayerTip.success('添加成功');
                    _this.showOverLayer(undefined, {});
                } else {
                    LayerTip.error(`添加失败，失败原因${res.msg}}`)
                }
            }).catch(e => {
                LayerTip.error(`添加失败，失败原因${e.message}}`)
        })
    }




}
// add by yanyj 20180724 end